let currentReport = null;
let currentPage = 1;
const pageSize = 12;

// JWT认证检查
const checkAuth = () => {


    console.log('task-report-management.html: 开始认证检查');
    if (!window.AuthManager || !AuthManager.isAuthenticated()) {
        console.log('用户未认证，重定向到登录页');
        AuthManager.redirectToLogin();
        return;
    }
    // 检查token有效性
    AuthManager.verifyToken()
        .then(() => {
            console.log('Token验证成功，初始化页面');
            pageInit();
        })
        .catch(error => {
            console.error('Token验证失败:', error);
            AuthManager.redirectToLogin();
        });
};

// 页面初始化
function pageInit() {
    loadReports();
    loadReporters();
    loadStatistics();
    setupEventListeners();
    if (window.PermissionManager) {
        PermissionManager=window.PermissionManager;
        PermissionManager.initReportPermissions();
    }
}

// 设置事件监听器
function setupEventListeners() {
    // 时间范围筛选变化时处理
    document.getElementById('timeRangeFilter').addEventListener('change', function() {
        const timeRange = this.value;
        const startDateInput = document.getElementById('startDateFilter');
        const endDateInput = document.getElementById('endDateFilter');
        if (timeRange === 'custom') {
            startDateInput.disabled = false;
            endDateInput.disabled = false;
        } else {
            startDateInput.disabled = true;
            endDateInput.disabled = true;
            startDateInput.value = '';
            endDateInput.value = '';
        }
        applyFilters();
    });
    // 新照片文件选择处理
    document.getElementById('newPhotos').addEventListener('change', function() {
        const files = this.files;
        const descriptionsDiv = document.getElementById('newPhotoDescriptions');
        descriptionsDiv.innerHTML = '';
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const div = document.createElement('div');
            div.className = 'mb-2';
            div.innerHTML = `
                <div class="input-group">
                    <span class="input-group-text">照片 ${i + 1}</span>
                    <input type="text" class="form-control" placeholder="照片描述" 
                           name="photoDescription_${i}" value="${file.name}">
                </div>
            `;
            descriptionsDiv.appendChild(div);
        }
    });
}

// 加载报告列表
async function loadReports(filters = {}) {
    try {
        const headers = new Headers(AuthManager.getAuthHeaders());
        headers.append('Content-Type', 'application/json');
        // 构建查询参数
        const queryParams = new URLSearchParams();
        if (filters.eventId) queryParams.append('eventId', filters.eventId);
        if (filters.reporterId) queryParams.append('reporterId', filters.reporterId);
        if (filters.startDate) queryParams.append('startDate', filters.startDate);
        if (filters.endDate) queryParams.append('endDate', filters.endDate);
        if (filters.timeRange) queryParams.append('timeRange', filters.timeRange);
        queryParams.append('page', currentPage);
        queryParams.append('size', pageSize);
        const url = `/ercms/api/completion/reports${queryParams.toString() ? '?' + queryParams.toString() : ''}`;
        const response = await fetch(url, {
            headers
        });
        const result = await response.json();
        if (result.success) {
            displayReports(result.data.content || result.data);
            updatePagination(result.data.totalElements || result.data.length);
        } else {
            console.error('加载报告失败:', result.message);
            document.getElementById('reportsContainer').innerHTML = 
                '<div class="col-12 text-center"><p>加载报告失败</p></div>';
        }
    } catch (error) {
        console.error('加载报告失败:', error);
        document.getElementById('reportsContainer').innerHTML = 
            '<div class="col-12 text-center"><p>加载报告失败</p></div>';
    }
}

// 显示报告列表
function displayReports(reports) {
    const container = document.getElementById('reportsContainer');
    if (!reports || reports.length === 0) {
        container.innerHTML = '<div class="col-12 text-center"><p>暂无报告数据</p></div>';
        return;
    }
    let html = '';
    reports.forEach(report => {
        const contentPreview = report.content ? 
            (report.content.length > 100 ? report.content.substring(0, 100) + '...' : report.content) : 
            '无内容';
        html += `
            <div class="col-md-6 col-lg-4 mb-3">
                <div class="card report-card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <h6 class="card-title">事件 #${report.eventId}</h6>
                            <small class="text-muted">${formatDateTime(report.reportTime)}</small>
                        </div>
                        <p class="card-text content-preview">${contentPreview}</p>
                        <div class="mb-2">
                            <small class="text-muted">
                                <i class="bi bi-person"></i> ${report.reporterName || '未知用户'}
                            </small>
                        </div>
                        ${report.photos && report.photos.length > 0 ? `
                            <div class="mb-2">
                                <small class="text-muted">
                                    <i class="bi bi-image"></i> ${report.photos.length} 张照片
                                </small>
                                <div class="mt-1">
                                    ${report.photos.slice(0, 3).map(photo => `
                                        <img src="/ercms/api/completion/photos/${photo.id}/file" 
                                             class="photo-preview me-1" 
                                             alt="照片预览"
                                             onclick="viewPhoto('/ercms/api/completion/photos/${photo.id}/file')">
                                    `).join('')}
                                    ${report.photos.length > 3 ? `<small class="text-muted">+${report.photos.length - 3}</small>` : ''}
                                </div>
                            </div>
                        ` : ''}
                        <div class="d-flex gap-2">
                            <button class="btn btn-primary btn-sm" onclick="viewReportDetail(${report.id})">
                                <i class="bi bi-eye"></i> 查看详情
                            </button>
                            <button class="btn btn-info btn-sm" onclick="navigateToEventFromList(${report.eventId})">
                                <i class="bi bi-arrow-right"></i> 查看事件
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    container.innerHTML = html;
}

// 更新分页
function updatePagination(totalElements) {
    const totalPages = Math.ceil(totalElements / pageSize);
    const pagination = document.getElementById('pagination');
    if (totalPages <= 1) {
        pagination.innerHTML = '';
        return;
    }
    let html = '';
    // 上一页
    html += `
        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${currentPage - 1})">上一页</a>
        </li>
    `;
    // 页码
    for (let i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) {
        html += `
            <li class="page-item ${i === currentPage ? 'active' : ''}">
                <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
            </li>
        `;
    }
    // 下一页
    html += `
        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${currentPage + 1})">下一页</a>
        </li>
    `;
    pagination.innerHTML = html;
}

// 切换页面
function changePage(page) {
    currentPage = page;
    applyFilters();
}

// 加载报告人列表
async function loadReporters() {
    try {
        const headers = new Headers(AuthManager.getAuthHeaders());
        const response = await fetch('/ercms/api/users', {
            headers
        });
        const result = await response.json();
        if (result.success) {
            const reporterFilter = document.getElementById('reporterFilter');
            let options = '<option value="">全部报告人</option>';
            result.data.forEach(user => {
                options += `<option value="${user.id}">${user.realName || user.username}</option>`;
            });
            reporterFilter.innerHTML = options;
        }
    } catch (error) {
        console.error('加载报告人失败:', error);
    }
}

// 加载统计数据
async function loadStatistics() {
    try {
        const headers = new Headers(AuthManager.getAuthHeaders());
        const response = await fetch('/ercms/api/completion/statistics', {
            headers
        });
        const result = await response.json();
        if (result.success) {
            document.getElementById('totalReports').textContent = result.data.totalReports || 0;
            document.getElementById('todayReports').textContent = result.data.todayReports || 0;
            document.getElementById('weekReports').textContent = result.data.weekReports || 0;
            document.getElementById('monthReports').textContent = result.data.monthReports || 0;
        }
    } catch (error) {
        console.error('加载统计数据失败:', error);
    }
}

// 应用筛选
function applyFilters() {
    const filters = {
        eventId: document.getElementById('eventIdFilter').value,
        reporterId: document.getElementById('reporterFilter').value,
        timeRange: document.getElementById('timeRangeFilter').value,
        startDate: document.getElementById('startDateFilter').value,
        endDate: document.getElementById('endDateFilter').value
    };
    // 移除空值
    Object.keys(filters).forEach(key => {
        if (!filters[key]) {
            delete filters[key];
        }
    });
    currentPage = 1; // 重置到第一页
    loadReports(filters);
}

// 清除筛选
function clearFilters() {
    document.getElementById('eventIdFilter').value = '';
    document.getElementById('reporterFilter').value = '';
    document.getElementById('timeRangeFilter').value = '';
    document.getElementById('startDateFilter').value = '';
    document.getElementById('endDateFilter').value = '';
    document.getElementById('startDateFilter').disabled = true;
    document.getElementById('endDateFilter').disabled = true;
    currentPage = 1;
    loadReports();
}

// 查看报告详情
async function viewReportDetail(reportId) {
    try {
        const headers = new Headers(AuthManager.getAuthHeaders());
        const response = await fetch(`/ercms/api/completion/reports/${reportId}`, {
            headers
        });
        const result = await response.json();
        if (result.success) {
            currentReport = result.data;
            displayReportDetail(result.data);
            const modal = new bootstrap.Modal(document.getElementById('reportDetailModal'));
            modal.show();
        } else {
            alert('加载报告详情失败: ' + result.message);
        }
    } catch (error) {
        console.error('加载报告详情失败:', error);
        alert('加载报告详情失败');
    }
}

// 显示报告详情
function displayReportDetail(report) {
    const contentDiv = document.getElementById('reportDetailContent');
    let html = `
        <div class="row">
            <div class="col-md-8">
                <h6>报告内容</h6>
                <p>${report.content || '无内容'}</p>
            </div>
            <div class="col-md-4">
                <h6>报告信息</h6>
                <p><strong>事件ID:</strong> ${report.eventId}</p>
                <p><strong>报告人:</strong> ${report.reporterName || '未知用户'}</p>
                <p><strong>报告时间:</strong> ${formatDateTime(report.reportTime)}</p>
            </div>
        </div>
    `;
    if (report.photos && report.photos.length > 0) {
        html += `
            <div class="mt-4">
                <h6>现场照片 (${report.photos.length} 张)</h6>
                <div class="row">
                    ${report.photos.map(photo => `
                        <div class="col-md-4 mb-3">
                            <img src="/ercms/api/completion/photos/${photo.id}/file" 
                                 class="img-fluid rounded" 
                                 alt="现场照片"
                                 style="max-height: 200px; object-fit: cover; cursor: pointer;"
                                 onclick="viewPhoto('/ercms/api/completion/photos/${photo.id}/file')">
                            <p class="mt-1 small text-muted">${photo.description || '无描述'}</p>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
    }
    contentDiv.innerHTML = html;
}

// 编辑报告
function editReport() {
    if (!currentReport) return;
    // 填充编辑表单
    document.getElementById('editContent').value = currentReport.content || '';
    // 显示现有照片
    const existingPhotosDiv = document.getElementById('existingPhotos');
    if (currentReport.photos && currentReport.photos.length > 0) {
        existingPhotosDiv.innerHTML = currentReport.photos.map(photo => `
            <div class="col-md-4 mb-2">
                <div class="position-relative">
                    <img src="/ercms/api/completion/photos/${photo.id}/file" 
                         class="img-fluid rounded" 
                         alt="照片"
                         style="max-height: 100px; object-fit: cover;">
                    <button type="button" class="btn btn-danger btn-sm position-absolute top-0 end-0"
                            onclick="deletePhoto(${photo.id})" style="font-size: 0.5rem;">
                        <i class="bi bi-x"></i>
                    </button>
                </div>
            </div>
        `).join('');
    } else {
        existingPhotosDiv.innerHTML = '<p class="text-muted">暂无照片</p>';
    }
    // 关闭详情模态框，打开编辑模态框
    const detailModal = bootstrap.Modal.getInstance(document.getElementById('reportDetailModal'));
    detailModal.hide();
    const editModal = new bootstrap.Modal(document.getElementById('editReportModal'));
    editModal.show();
}

// 删除照片
async function deletePhoto(photoId) {
    if (!confirm('确定要删除这张照片吗？')) return;
    try {
        const headers = new Headers(AuthManager.getAuthHeaders());
        const response = await fetch(`/ercms/api/completion/photos/${photoId}`, {
            method: 'DELETE',
            headers
        });
        if (response.ok) {
            // 重新加载报告详情
            await viewReportDetail(currentReport.id);
            alert('照片删除成功');
        } else {
            const result = await response.json();
            alert('删除照片失败: ' + result.error);
        }
    } catch (error) {
        console.error('删除照片失败:', error);
        alert('删除照片失败');
    }
}

// 提交编辑报告
async function submitEditReport() {
    if (!currentReport) return;
    const content = document.getElementById('editContent').value.trim();
    if (!content) {
        alert('请输入报告内容');
        return;
    }
    try {
        const formData = new FormData();
        formData.append('content', content);
        // 添加新照片
        const newPhotos = document.getElementById('newPhotos').files;
        for (let i = 0; i < newPhotos.length; i++) {
            formData.append('photos', newPhotos[i]);
            const description = document.querySelector(`input[name="photoDescription_${i}"]`).value;
            formData.append('descriptions', description);
        }
        const headers = new Headers(AuthManager.getAuthHeaders());
        // 不设置Content-Type，浏览器会自动设置multipart/form-data
        const response = await fetch(`/ercms/api/completion/${currentReport.id}/with-photos`, {
            method: 'PUT',
            headers,
            body: formData
        });
        const result = await response.json();
        if (result.success) {
            alert('报告修改成功');
            // 关闭编辑模态框
            const editModal = bootstrap.Modal.getInstance(document.getElementById('editReportModal'));
            editModal.hide();
            // 重新加载报告列表
            loadReports();
        } else {
            alert('修改报告失败: ' + result.error);
        }
    } catch (error) {
        console.error('修改报告失败:', error);
        alert('修改报告失败');
    }
}

// 删除报告
async function deleteReport() {
    if (!currentReport) return;
    if (!confirm('确定要删除这份报告吗？此操作不可恢复！')) return;
    try {
        const headers = new Headers(AuthManager.getAuthHeaders());
        const response = await fetch(`/ercms/api/completion/reports/${currentReport.id}`, {
            method: 'DELETE',
            headers
        });
        if (response.ok) {
            alert('报告删除成功');
            // 关闭详情模态框
            const detailModal = bootstrap.Modal.getInstance(document.getElementById('reportDetailModal'));
            detailModal.hide();
            // 重新加载报告列表
            loadReports();
        } else {
            const result = await response.json();
            alert('删除报告失败: ' + result.error);
        }
    } catch (error) {
        console.error('删除报告失败:', error);
        alert('删除报告失败');
    }
}

// 导航到事件
function navigateToEvent() {
    if (!currentReport) return;
    window.location.href = `/ercms/dispatch/event/${currentReport.eventId}`;
}

// 从列表导航到事件
function navigateToEventFromList(eventId) {
    window.location.href = `/ercms/dispatch/event/${eventId}`;
}

// 查看照片
function viewPhoto(photoUrl) {
    document.getElementById('photoViewImage').src = photoUrl;
    const modal = new bootstrap.Modal(document.getElementById('photoViewModal'));
    modal.show();
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '-';
    try {
        const date = new Date(dateTimeStr);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    } catch (error) {
        return dateTimeStr;
    }
}

// 页面加载完成后进行认证检查
document.addEventListener('DOMContentLoaded', checkAuth); 